<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 添加按钮区域 -->
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="openAddCateDialogVisible">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table
        :data="cateList.result"
        style="width: 100%"
        row-key="cat_id"
        border
      >
        <el-table-column type="index" width="50" label="#"></el-table-column>

        <el-table-column label="分类名称">
          <template #default="scope">{{ scope.row.cat_name }}</template>
        </el-table-column>

        <el-table-column label="是否有效">
          <template #default="scope"><el-switch :model-value="!scope.row.cat_deleted"/></template>
        </el-table-column>

        <el-table-column label="排序">
          <template #default="scope">
            <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
            <el-tag class="ml-2" type="success" v-else-if="scope.row.cat_level == 1">二级</el-tag>
            <el-tag class="ml-2" type="warning" v-else-if="scope.row.cat_level == 2">三级</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openEditCateDialogVisible(scope.row)"> 编辑 </el-button>
            <el-button type="danger" size="small" @click="deleteCate(scope.row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-model:currentPage="queryInfo.pagenum"
        v-model:page-size="queryInfo.pagesize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog v-model="addCateDialogVisible" title="添加分类" width="30%" center @close="addCateDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="90px">

        <el-form-item label="分类名称:" prop="cat_name" >
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级级别:" prop="password" >
          <!-- options 用来配置数据源 -->
          <!-- props 用来指定配置对象 -->
          <el-cascader 
            :options="parentCateList" 
            clearable 
            :props="cascaderProps" 
            v-model="selectedKeys" 
            @change="parentCateChanged"
            change-on-select
          />
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addCateDialogClosed">取消</el-button>
          <el-button type="primary" @click="addCate">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog v-model="editCateDialogVisible" title="编辑分类" width="30%" center @close="editCateDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="editCurrentCata" :rules="editCateFormRules" ref="editCateFormRef" label-width="90px">
        <el-form-item label="分类名称:" prop="cat_name" >
          <el-input v-model="editCurrentCata.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editCateDialogClosed">取消</el-button>
          <el-button type="primary" @click="editCateConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import axios from '../../http/axios.js'

export default {
  name: 'Cate',
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      cateList: [], // 商品分类的数据列表，默认为空
      total: 0,
      addCateDialogVisible: false, // 控制添加分类对话框的显示与否。
      addCateForm: {// 添加分类对象的表单数据。
        cat_name: '',
        cat_pid: 0, // 父级id
        cat_level: 0 // 分类的等级,默认添加一级分类
      }, 
      addCateFormRules: { // 添加分类表单的验证规则
        cat_name: [
          {
            required: true,
            message: '分类名称不能为空',
            trigger: 'blur'
          }
        ]
      },
      parentCateList: [],
      cascaderProps: { // 指定级联选择框的配置对象
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedKeys: [],// 选中的父级分类数组
      editCateDialogVisible: false,//编辑分类对话框的显示与隐藏
      editCurrentCata: {}, // 修改现在的分类
      editCateFormRules: {
        cat_name: [
          {
            required: true,
            message: '分类名称不能为空',
            trigger: 'blur'
          }
        ]
      },

    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      // 获取商品分类数据列表
      const { data: res } = await axios.get('categories', {
        params: this.queryInfo,
      })

      if (res.meta.status !== 200) {
        this.$message({
          type: 'error',
          message: '获取商品分类的数据列表失败',
        })
      } else {
        this.cateList = res.data;

        this.total = res.data.total
      }
    },
    handleSizeChange(newSize){ // 改变每页数据的条数
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },
    handleCurrentChange(newPageNum){ // 改变当前页数
      this.queryInfo.pagenum = newPageNum;
      this.getCateList();
    },
    addCateDialogClosed(){// 关闭添加分类对话框
      this.addCateDialogVisible = false;
      this.addCateForm = {
        cat_name:'',
        cat_pid: 0,
        cat_level: 0
      };
      this.parentCateList = [];
      this.selectedKeys = [];
    },
    async getParentCateList(){
      const { data: res} = await axios.get('categories',{params: { type: 2}});

      if(res.meta.status !== 200){
        this.$message({
          type: 'error',
          message: '获取父级分类数据表失败'
        });
        return false;
      }else{
        this.parentCateList = res.data;
        return true;
      }

    },
    openAddCateDialogVisible(){ // 打开添加分类对话框
     const parentList = this.getParentCateList();

     if(parentList){
      this.addCateDialogVisible = true;
     }
    },
    parentCateChanged(){ // 选择项发生变化触发这个函数。
      if(this.selectedKeys.length > 0){
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
      };
    },
    addCate(){
      this.$refs.addCateFormRef.validate(async (valid) => {
        if(valid){
          const { data: res} = await axios.post('categories',this.addCateForm);

          if(res.meta.status !== 201){
            return this.$message({
              type: 'error',
              message: '添加失败'
            })
          }else{
            this.$message({
              type: 'success',
              message: '添加成功'
            });
            this.addCateDialogClosed();
            this.getCateList();
          };

        }
      })
    },
    openEditCateDialogVisible(cateData){ // 打开分类编辑对话框按钮
      this.editCurrentCata = cateData;
      this.editCateDialogVisible = true;
    },
    editCateDialogClosed(){// 关闭编辑分类对话框
      this.editCateDialogVisible = false;
      this.editCurrentCata = {};
    },
    editCateConfirm(){ //确认修改分类
      this.$refs.editCateFormRef.validate(async valid => {
        if(valid){
          const { data: res} = await axios.put(`categories/${this.editCurrentCata.cat_id}`,{ cat_name: this.editCurrentCata.cat_name});

          if(res.meta.status !== 200){
            this.$message({
              type: 'error',
              message: '修改分类错误'
            })
          }else{
            this.$message({
              type: 'success',
              message: '修改分类成功'
            });
            this.editCateDialogClosed();
          }
        }
      })
    },
    deleteCate(cateInfo){// 删除分类
      this.$messageBox.confirm("你确认要永久删除该分类吗",'删除分类',{
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        const { data: res} = await axios.delete(`categories/${cateInfo.cat_id}`);
        
        if(res.meta.status !== 200){
          this.$message({
            type: 'error',
            message: '删除失败'
          });
        }else {
          this.$message({
            type: 'success',
            message: '删除成功'
          });
          this.getCateList();
        }
      }).catch(() => {
        // 取消删除
      });
    }
  },
}
</script>

<style>
</style>